<?php

namespace App\Supports\WithdrawFreelance\XinZhongBao;

use Exception;
use App\Models\User;
use App\Models\BankCard;
use App\Models\Freelance;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use GuzzleHttp\Client;
use Brick\Math\RoundingMode;
use Rainsens\Dinglog\Facades\Dinglog;

class XinZhongBao
{
	protected $service_url = 'http://taxpay.jiangxixz.com/api';

	public function __construct(User $user)
	{
		$this->config = config('xinzhongbao');
		$this->merchantNo = $this->config['merchantNo'];
		/*$this->config['pub_key'] = chunk_split($this->config['pub_key'], 64, "\n");
		$this->config['pri_key'] = chunk_split($this->config['pri_key'], 64, "\n");*/
		$this->pub_key = "-----BEGIN PUBLIC KEY-----\n".$this->config['pub_key']."\n-----END PUBLIC KEY-----";
		$this->pri_key = "-----BEGIN PRIVATE KEY-----\n".$this->config['pri_key']."\n-----END PRIVATE KEY-----";
		
		$this->localUser = $user;

		if (!$this->localUser->isPhoneBound()) {
			abort(400, '会员账号手机号码未绑定');
		}
	}
	
	/*
     * 用户进件
     */

    public function addMerchant($param){

        $method        = '/freelancer/v2/signUp';
        $param_ary  = array(
            'name'              => $param['name'],
            'idCardNo'          => $param['idCardNo'],
        );
        
        $ret    = $this->_public_request($param_ary,$method);
        return $ret;
    }

    /*
     * 出款
     */
    public function pay($param){
        $method      = '/settle/v1/pay';

        $payItems   = array();
        foreach ($param['list'] as $order_mess){
            $payItems[] = array(
                'orderNumber'   => $order_mess['orderNumber'], // 订单号
                'payAmount'     => $order_mess['payAmount'], // 金额
                'payeeName'     => $order_mess['payeeName'], // 收款人名称
                'payeeAcc'      => $order_mess['payeeAcc'], // 收款人账号
                'idCard'        => $order_mess['idCard'], // 身份证号
                'mobile'        => $order_mess['mobile'], // 手机号
                'memo'          => '业绩提成',
                'payType'       => '0', //代付类型 0:实时 1:工作日
                'paymentType'   => '0', //代付方式 0:银行卡，1:支付宝，2:微信
                'accType'       => '1', //结算银行卡账号类型，0:对公，1:对私
            );
        }

        $param_ary  = array(
            'totalCount'       => $param['totalCount'],
            'totalAmt'         => $param['totalAmt'],
            'batchNo'          => $param['batchNo'],
            'payItems'         => $payItems,
        );
        $ret    = $this->_public_request($param_ary,$method);
        return $ret;
    }

    /*
     * 查询
     */
    public function orderQuery($param)
    {
        $method      = '/settle/v1/payQuery';

        $payItems   = array();
        foreach ($param['list'] as $order_mess){
            $payItems[] = array(
                'orderNumber'   => $order_mess['orderNumber'], // 订单号
                'transOrderNum' => $order_mess['transOrderNum'], // 订单流水号
            );
        }

        $param_ary  = array(
            'batchNo'          => $param['batchNo'],
            'queryItems'       => $payItems,
        );
        $ret    = $this->_public_request($param_ary,$method);
        return $ret;
    }


    //**********************************************工具类***************************************************

    public function _public_request($param,$method)
    {
        $api_url    = $this->service_url.$method;

        $aes_key    = $this->getAESKey(16);
        $encryptKey = $this->rsaEncode($aes_key);
        $encryptData= $this->AESEncrypt(json_encode($param),$aes_key);
        $sign       = $this->_rsa_sign(json_encode($param));

        $param_ary  = array(
            'merchantNo'    => $this->merchantNo,
            'encryptKey'    => $encryptKey,
            'encryptData'   => $encryptData,
            'sign'          => $sign
        );
        $result         = $this->sendHttpRequest($param_ary,$api_url);
        $result_array   = json_decode($result,true);

        Dinglog::text("========== xzb debug {$result}......");
        $get_data       = $result_array['data'];
        $get_data       = json_decode($get_data,true);
        //*********** 解密数据******************
        $key            = $this->rsaDecode($get_data['encryptKey']);
        $new_date       = $this->AESDecrypt($get_data['encryptData'],$key);
        $result_array['data'] = json_decode($new_date,true);

        return $result_array;
    }

    //生成AES Key
    public  function getAESKey($num){
        $init_str    = '1234567890abcdefghijklmnopqrstuvwxyz';
        $return_str  = '';
        for($i = 1; $i <= $num; $i++){
            $no     = rand(0,35);
            $return_str .= $init_str[$no];
        }
        return $return_str;
    }

    /*
     *  ********************** AES加密解密 **********************
     */
    public function AESEncrypt($data,$key){
        if (is_array($data)){
            $data = json_encode($data);
        }
        $result =  openssl_encrypt($data, 'AES-128-ECB', $key,  1 );
        return base64_encode($result);
    }
    //AES 解密
    public function AESDecrypt($data,$key){
        $encryptedData = base64_decode($data);
        $result        = openssl_decrypt($encryptedData, 'AES-128-ECB', $key, 1);
        return $result;
    }

    /*
    * **********************  RSA签名  **********************
    */
    private function _rsa_sign($paramStr){
        $pri_key            = openssl_pkey_get_private($this->pri_key);
        openssl_sign($paramStr, $encryptData, $pri_key, OPENSSL_ALGO_SHA1);
        openssl_free_key($pri_key);
        return base64_encode($encryptData);
    }

    /*
     * **********************   ras加解密  ***************
     */
    public function rsaEncode($rands) {
        $public_key     = $this->pub_key;
        $pu_key         = openssl_pkey_get_public($public_key);
        openssl_public_encrypt($rands,$encrypted, $pu_key,OPENSSL_PKCS1_PADDING);
        $encryptKey     = base64_encode($encrypted);
        return $encryptKey;
    }

    public function rsaDecode($rands) {
        $rands          = base64_decode($rands);
        $private_key    = $this->pri_key;
        $pri_key        = openssl_pkey_get_private($private_key);
        openssl_private_decrypt($rands,$encrypted, $pri_key,OPENSSL_PKCS1_PADDING);
        return $encrypted;
    }

    /*
     * **********************   数据请求  **********************
     */
    private function sendHttpRequest($data,$url)
    {
        $opts = $data;
        if (is_array($data)){
            $opts = json_encode($data);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不验证HOST
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // 链接超时
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json;charset=UTF-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $opts);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 运行cURL，请求网页
        $html = curl_exec($ch);
        curl_close($ch);
        return $html;

    }
   
}
